﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SimpleJson;
using System;
using Pomelo.DotNetClient;
using System.Threading;
using System.Collections;

public class joinroom : MonoBehaviour {

    PomeloClient pc;
    public static string HandShakeKey = "agashgw123pajloaxn34ga8xrunpagkjwlaw456xnpaagl29w4rxn";

    public string uid = "robot_800500";
    public string rid = "550370";
	// Use this for initialization
	void Start () {

        login();
	}
    public void login()
    {
        string host = "120.76.182.17";
        int port = 8821;
        //string host = "120.76.182.17";
        //int port = 8720;
        pc = new PomeloClient();


        pc.initClient(host, port);
        pc.NetWorkStateChangedEvent += (state) =>
        {
            Console.WriteLine("net change : " + state);
        };
        JsonObject shakemsg = new JsonObject();
        shakemsg["key"] = HandShakeKey;
        string str = uid;// + Mathf.Floor(UnityEngine.Random.value * 99999);
        //0.握手的时候 带上 这个key， 不带的话我这边就会跑去链接
        pc.connect(shakemsg, (data) =>
        {
            Debug.Log("connection compelete" + data);
            JsonObject msg = new JsonObject();
            //msg["openid"] = openid;
            //msg["access_token"] = acccess_token;
            msg["openid"] = str;
            msg["access_token"] = "robot_immunity";
            // 1. platform server 用户登入  登入后返回  
            //{"code":0,"uid":10000,"token":"99ce344a8b7c2fe5c3b3f416f5fa3cade8e2fe44bfa37a045fb53358f72ddf0f","host":"127.0.0.1","port":3010}
            pc.request("platform.platformHandler.Author", msg, OnQuery);
        });
    }
    void OnQuery(JsonObject result)
    {
        Debug.Log(result);
        if (Convert.ToInt32(result["code"]) == 0)
        {
            pc.disconnect();

            string host = (string)result["host"];
            int port = Convert.ToInt32(result["port"]);
            pc = new PomeloClient();
            pc.initClient(host, port);
            JsonObject shakemsg = new JsonObject();
            shakemsg["key"] = HandShakeKey;
            //同样带上key
            pc.connect(shakemsg, (data) =>
            {
                Debug.Log("connection compelete" + data);
                JsonObject msg = new JsonObject();
                msg["uid"] = result["uid"];
                msg["token"] = result["token"];
                //2. connector登入操作 返回用户信息
                //{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"127.0.0.1","cardNum":8}
                pc.request("connector.userHandler.Login", msg, OnLogin);


            });
            pc.on("OnMessage", (gmsg) =>
            {
                Debug.Log("OnMessage:" + gmsg);
            });

            #region update 20 16 11 07
            //监控网络状态
            pc.NetWorkStateChangedEvent += (state) =>
            {
                Console.WriteLine("net change : " + state);
            };


            //{"cardNum":8} 自己房卡数量发生变化更新
            pc.on("OnCardUpdate", (gmsg) =>
            {
                Debug.Log("OnCardUpdate:" + gmsg);
            });
            /*
             * 退出出房间，
             * 所有退出房间都用这个，
             * 游戏开始后，点击即会出现投票推出框。
             * 
             * 游戏未开始，非房主会直接退出。
             * 
             * 房主则会立刻解散房间。
             */
            JsonObject arg = new JsonObject();
            pc.request("game.roomHandler.leaveRoom", arg, (sret) =>
            {
                Debug.Log("Leavel" + sret);
            });

            /*
             * 有其它玩家加入房间
             * 数据结构如下,idx指明在房间的哪个位置
             * {"uid":10390,"idx":3,"ready":0,"info":{"uid":10390,"name":"robot_10002","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"127.0.0.1"}}
             */
            pc.on("OnAdd", (gmsg) =>
            {
                Debug.Log("OnAdd:" + gmsg);
            });

            /*有玩家离开了房间
             * 数据结构如下， idx为 1的玩家离开了房间
             * {idx: 1}
             */
            pc.on("OnLeave", (gmsg) =>
            {
                Debug.Log("OnLeave:" + gmsg);
            });

            //{"room":0} 房间被关闭的时候，自己的房间id设置成0，玩家自己退出或者房间被解散
            pc.on("OnRoomClose", (gmsg) =>
            {
                Debug.Log("OnRoomClose:" + gmsg);
            });
            //申请解散房间的内容
            /*
             *{1:0, 1:0, 2:1, 3: 2}  0,1,2分别表示  未知，拒绝  同意
             *
             *更新也是调用这个
             *
             */
            pc.on("OnChoose", (gmsg) =>
            {
                Debug.Log("OnChoose:" + gmsg);
            });
            /* 申请解散的窗口关闭
             *  无数据
             */
            pc.on("OnChooseClose", (gmsg) =>
            {
                Debug.Log("OnChoose:" + gmsg);
            });
            /*
             * 返回房间的update信息，断线重连使用
             * {
             *   level: 5 当前打到第5局
             *   closer:{1:0, 1:0, 2:1, 3: 2}  同上面的OnChoose 
             * }
             */
            pc.request("game.roomHandler.getRoomUpdate", arg, (sret) =>
            {
                Debug.Log("getRoomUpdate" + sret);
            });
            /*
             * 返回房间的update信息， 完全断开后的返回  痛create room 、 join room
             * {
             *   level: 5 当前打到第5局
             *   closer:{1:0, 1:0, 2:1, 3: 2}  同上面的OnChoose 
             * }
             */
            pc.request("game.roomHandler.getRoomInfo", arg, (sret) =>
            {
                Debug.Log("getRoomUpdate" + sret);
            });
            #endregion
        }
    }
    void OnLogin(JsonObject result)
    {
        Debug.Log(result);
        JsonObject msg = new JsonObject();
        //获取用户信息
        pc.request("connector.userHandler.getUserInfo", msg, (ret) =>
        {
            Debug.Log("getUserInfo" + ret);
        });

        //获取用户  更新信息，断线后重连使用
        /* 
           只返回会更新的用户信息，如
         *{room: 0, cardNum: 8}
         *房间号为0 玩家不在房间
         *身上房卡 8张
         */
        pc.request("connector.userHandler.getUserUpdate", msg, (ret) =>
        {
            Debug.Log("getUserUpdate" + ret);
        });

        //获取自己的录像列表  返回{"data":[{"rid":1000096,"room":100001，"date":1480153867133,"players":[{"name":"robot_72077","uid":10791},{"name":"robot_10000","uid":10388},{"name":"robot_10001","uid":10389},{"name":"robot_10002","uid":10390}]}]}
        pc.request("connector.userHandler.getUserRecords", msg, (ret) =>
        {
            Debug.Log("getUserRecords" + ret);
        });
        pc.request("connector.userHandler.getPublicMessage", msg, (ret) =>
        {
            Debug.Log("getPublicMessage" + ret);
        });
        //观看某场录像，可以看任何的录像 只要输入id
        msg["rid"] = "100005";
        pc.request("connector.userHandler.getRecord", msg, (ret) =>
        {
            Debug.Log("getRecord" + ret);
        });

        //JsonObject talk = new JsonObject();
        //string strName = System.IO.File.ReadAllText("F:/Temp/1.txt");
        //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strName);
        ////byte[] news =  DecodeToByte(EncodeToInt(bytes));

        ////int[] arr = EncodeToInt(bytes);

        //talk["msg"] = new List<object>(EncodeToInt(bytes));
        //pc.request("game.chatHandler.sendBytes", talk, (sret) =>
        //{
        //    Debug.Log("sendBytes：" + sret);
        //});
        //pc.on("OnChatBytes", (gmsg) =>
        //{
        //    object[] arr = ((List<object>)gmsg["msg"]).ToArray();
        //    byte[] bts = DecodeToByte(arr);
        //    Debug.Log(System.Text.Encoding.UTF8.GetString(bts));
        //    Debug.Log("OnChatBytes:" + gmsg);
        //});
        //pc.request("connector.userHandler.joinRoom", msg, (ret) =>
        //{
        //    Debug.Log(ret);

        //});
        pc.on("OnChat", (gmsg) =>
        {
            Debug.Log("OnChat:" + gmsg);
        });
        msg["rid"] = rid;
        //创建房间
        pc.request("connector.userHandler.joinRoom", msg, (vret) =>
        {
            Debug.Log(vret);
            JsonObject arg = new JsonObject();
            arg["rid"] = vret["id"];
            rid = vret["id"] as string;
            //CreateOther(vret["id"] as string);
            //加入房间

            /*
             * 返回房间信息，
             * 主要有 id  房价id
             * opt  属性
             * users 玩家数组[]
             *      玩家信息 uid  玩家id
             *               idx  玩家编号！在游戏里面都是用这个来描述。0，1,2,3分别表示 房主，然后逆时针的三个玩家。这里需要判断uid跟自己的uid一样，那么用那个idx请求
             *               info  头像ip等信息
             {"id":105000,"opt":{"ma":6,"gui":1,"qidui":1,"qiang":1,"qupai":16,"quanbao":6,"xuangui":false},"users":[{"uid":10000,"idx":0,"info":{"name":"3D Coffice","sex":1,
             * "head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}},{"uid":10000,"idx":1,"info":{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}},{"uid":10000,"idx":2,"info":{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}}]}
             
             */
            //pc.request("game.roomHandler.getRoomUpdate", arg, (sret) =>
            //{
            //    Debug.Log("getRoomUpdate" + sret);
            //});

            //pc.request("game.roomHandler.getRoomInfo", arg, (sret) =>
            //{
            //    Debug.Log("getRoomUpdate" + sret);
            //});
            //pc.request("game.roomHandler.leaveRoom", arg, (sret) =>
            //{
            //    Debug.Log("Leavel" + sret);
            //});

            //pc.request("connector.userHandler.joinRoom", arg, (ret) =>
            //{
            //    Debug.Log(ret);

            //});

            pc.on("OnAdd", (gmsg) =>
            {
                Debug.Log("OnAdd:" + gmsg);
            });

            pc.on("OnLeave", (gmsg) =>
            {
                Debug.Log("OnLeave:" + gmsg);
            });

            pc.on("OnClose", (gmsg) =>
            {
                Debug.Log("OnClose:" + gmsg);
            });

            pc.on("OnAgree", (gmsg) =>
            {
                Debug.Log("OnAgree:" + gmsg);
            });
            /*
             {"host":0,"gui":33,"remain":3,"players":[{"card":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000}]}
             
             * 前言 牌0-33 依次表示  1-9 万  1-9饼  1-9条  字
             * 
             * host 庄家
             * gui  -1是无鬼
             * remain 剩余卡牌
             * players 玩家数组:
             *          card 手牌 其它人的手牌未知，只有张数
             *          his  已经出的牌
             *          heap [{t:0,v:1}]等于旁边的牌 t 0 1 2 3 碰 点杠 明杠 暗杠 v值
             *          score 分数
             */
            pc.on("OnStart", (gmsg) =>
            {
                Debug.Log("Start:" + gmsg);
            });

            /*广播  玩家idx补一张牌
             * 其它的玩家收到的是
             * idx为0的哥们补了一张牌
             * {"idx":0}
             * 
             * Draw:{"idx":0,"val":4}
             * 
             */
            pc.on("OnDraw", (gmsg) =>
            {
                Debug.Log("Draw:" + gmsg);
            });


            /* 单独请求你，要求你出牌
               op 类型位运算的组,看上面的OperationResult   OperationResult.Hu|OperationResult.AnGang|OperationResult.None 就是同时可以胡也可以暗杠,也可以不出
               val 宣传就是牌值
             */
            pc.on("OnCall", (gmsg) =>
            {
                Debug.Log("Call:" + gmsg);
             
            });

            /*
             op val 就是上面操作的通知，通知所有玩家
             */
            pc.on("OnPlay", (gmsg) =>
            {
                Debug.Log("Play:" + gmsg);
            });
            /*
             {"ma":[0,16,13,22,30,0],"players":[{"card":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"his":[],"heap":[],"score":1006},{"card":[33,1,4,6,8,10,13,17,18,19,20,22,23],"his":[],"heap":[],"score":998},{"card":[33,3,9,9,10,14,19,22,24,26,26,27,29],"his":[],"heap":[],"score":998},{"card":[2,3,4,9,14,18,21,21,23,23,25,27,29],"his":[],"heap":[],"score":998}],"hu":{"0":{"mutil":2,"way":1,"cards":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"guiIdx":[],"zhong":[0,2,3,5]}}}
             游戏结算的通知
             *   ma  开的六章马牌
             *   players 玩家的游戏数据
             *   hu  胡的信息，里面可能有多个玩家一起胡
             *      mutil 倍率
             *      way  胡法   1<<n 位运算的方式表示
             *      cards 胡牌的队列 
             *      guiIdx 数组 表示上面card里面的idx是鬼变的 类似的cards[0, 1, 1, 1, 0], guiidx [2, 3] 里面的 2 、3位置的1是鬼变的
             *      zhong  中码，自己中码的信息 如[0,2,3,5],就是中了ma[0] ma[2] ma[3] ma[5]
             */
            pc.on("OnEnd", (gmsg) =>
            {
                Debug.Log("end:" + gmsg);
            });
        });


    }
	// Update is called once per frame
	void Update () {
	
	}
}
